package com.guochaojava.api;

import cn.hutool.core.lang.Console;
import com.guochaojava.model.Member;
import com.guochaojava.service.MemberService;
import com.guochaojava.util.Result;
import com.guochaojava.view.ClientInfoView;
import com.lgd.winter.wechat.content.mini.bean.result.MiniClientInfoResult;
import com.lgd.winter.wechat.core.WeChatTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 获取小程序登陆openid
 *
 * @author guochao
 */
@Api(value = "客户端信息接口", tags = "客户端信息接口")
@Controller
@RequestMapping("/api")
public class ClientInfoApi {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String CURRENT_URL = "/client";

    @Autowired
    private WeChatTemplate weChatTemplate;
    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "获取客户端openId,并返回用户是否保存过信息标识")
    @ResponseBody
    @RequestMapping(value = "/client/info", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jsCode", value = "登录时获取的code", required = true, dataType = "string", paramType = "query", example = "js_code")
    })
    public Object clientInfo(String jsCode) {
        try {
            ClientInfoView view = new ClientInfoView();
            MiniClientInfoResult result = weChatTemplate.opsForMini().getClientInfo(jsCode);
            Console.log("openID________:"+result);
            if (result.getErrcode() != 0) {
                return Result.buildError("操作失败！");
            }
            view.setOpenId(result.getOpenid());
            Member member = memberService.selectByOpenId(result.getOpenid());
            if (member != null) {
                view.setHas(true);
                view.setMember(member);
            }
            return Result.buildOK(view, "操作成功！");
        } catch (Exception e) {
            logger.error(CURRENT_URL, e);
            return Result.buildError("操作失败！");
        }
    }
}